<?php
namespace App\Admin\Controllers\OverSeasIn;

use App\Importer\OverSeasIn\OSImporter;
use App\Jobs\OverSeasIn\RemovaleOrderDetailStatus;
use App\Jobs\OverSeasIn\RemovaleOrderDetailUpload;
use App\Models\OverSeasBa\Warehouse;
use App\Models\OverSeasIn\RemovaleOrderDetail;
use App\Util\RExcel;
use Encore\Admin\Controllers\AdminController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use App\Models\OverSeasIn\RemovalePlan;
use Symfony\Component\HttpFoundation\File\UploadedFile;
class RemovaleDetailUploadController extends AdminController{

    protected $title = 'FBA移库明细上传';

    protected function grid()
    {
        $type = request('type');
        return view('overseas-in.removale-detail-upload.index',compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importConfirmShip(UploadedFile $file){
        try{
            $data = Excel::toArray(new OSImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $items = [];
            foreach($data as $row){
                $count++;
                $orderId = $row[0] ? trim($row[0]) : '';
                $sku = $row[1] ? trim($row[1]) : '';
                $shipNum = $row[2] ? trim($row[2]) : 0;
                $_status = $row[3] ? trim($row[3]) : '否';//未完结
                if(!$orderId || !$sku){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                $key = $orderId.'_'.$sku;
                if(!in_array($key,$arr)){
                    $arr[$count] = $key;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                if(!is_numeric($shipNum)){
                    $errors[$count] = '数量格式有误';
                    continue;
                }
                if($shipNum < 0){
                    $errors[$count] = '数量不能小于0';
                    continue;
                }
                if(!in_array($_status,['是','否'])){
                    $errors[$count] = $_status.'请选择是、否';
                    continue;
                }
                $status = array_search($_status,[2 => '是', 1 => '否']);
                if($status == 1 && $shipNum == 0){
                    $errors[$count] = '未完结状态实际数量不能为0';
                    continue;
                }
                DB::beginTransaction();
                $rod = RemovaleOrderDetail::query()->where('order_id',$orderId)->where('seller_sku',$sku)->first();
                if(!$rod){
                    $errors[$count] = $key.'列表不存在';
                    DB::rollBack();
                    continue;
                }
                if($rod->status == 2){
                    $errors[$count] = $key.'已完结勿重复完结';
                    DB::rollBack();
                    continue;
                }
                if(!$rod->warehouse_id){
                    $errors[$count] = $key.'未匹配到海外仓仓库';
                    DB::rollBack();
                    continue;
                }
                if($shipNum < $rod->ship_quantity){
                    $errors[$count] = $key.'实际数据小于已入库数量';
                    DB::rollBack();
                    continue;
                }
                $rod->this_quantity = $shipNum - $rod->ship_quantity;
                $rod->ship_quantity = $shipNum;
                // if($rod->ship_quantity >= $rod->shipped_quantity){
                //     $rod->status = 2;
                // }else{
                    $rod->status = $status;
                // }
                $flag = $rod->save();
                if(!$flag){
                    DB::rollBack();
                }else{
                    $items[] = $rod;
                    DB::commit();
                }
            }
            if(!empty($items)){
                //更新移库状态
                RemovaleOrderDetailStatus::dispatch($items);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    private function _importOrderWarehouse(UploadedFile $file){
        try{
            $data = Excel::toArray(new OSImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $arr = [];
            $items = [];
            foreach($data as $row){
                $count++;
                $_warehouse = $row[0] ? trim($row[0]) : '';
                $orderId = $row[1] ? trim($row[1]) : '';
                if(!$_warehouse || !$orderId){
                    $errors[$count] = '必填项为空';
                    continue;
                }
                if(!in_array($orderId,$arr)){
                    $arr[$count] = $orderId;
                }else{
                    $errors[$count] = '重复记录';
                    continue;
                }
                $warehouseId = Warehouse::getIdByCode($_warehouse);
                if(!$warehouseId){
                    $errors[$count] = '仓库'.$_warehouse.'系统不存在';
                    break;
                }
                $rod1Count = RemovaleOrderDetail::query()
                    ->where('order_id' , $orderId)
                    ->where('status' , 2)
                    ->count();
                if($rod1Count){
                    $errors[$count] = '订单已完结勿更新';
                    break;
                }
                $rpCount = RemovaleOrderDetail::query()
                    ->where('order_id' , $orderId)
                    ->where('status' , 1)
                    ->where('ship_quantity' , '>',0)
                    ->count();
                if($rpCount > 0){
                    $errors[$count] = '订单已入库勿更新';
                    break;
                }
                DB::beginTransaction();
                $flag = RemovalePlan::query()->updateOrCreate(
                    [
                        'order_id' => $orderId,
                    ],[
                    'warehouse_id' => $warehouseId
                    ]);
                if(!$flag){
                    DB::rollBack();
                }else{
                    $items[] = $orderId;
                    DB::commit();
                }
            }
            if(!empty($items)){
                //上传，移库明细数据
                RemovaleOrderDetailUpload::dispatch($items);
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }
}
